package com.JumpAndJump.service.impl;

import com.JumpAndJump.common.ServerResponse;
import com.JumpAndJump.dao.UserMapper;
import com.JumpAndJump.pojo.User;
import com.JumpAndJump.service.IUserService;
import com.JumpAndJump.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2018/1/7.
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
        private UserMapper userMapper;

        @Override
        public ServerResponse<User> login(String username, String password) {
            int resultCount = userMapper.checkUsername(username);
            if(resultCount == 0 ){
                return ServerResponse.createByErrorMessage("用户名不存在");
            }

            String md5Password = MD5Util.MD5EncodeUtf8(password);
            User user  = userMapper.selectLogin(username,md5Password);
            if(user == null){
                return ServerResponse.createByErrorMessage("密码错误");
            }

            user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
            return ServerResponse.createBySuccess(user.getUerid().toString(),user);
        }

    @Override
    public ServerResponse<String> register(String username,String password) {
        ServerResponse validResponse = this.checkValidUsername(username);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        //MD5加密
        password = MD5Util.MD5EncodeUtf8(password);
        int resultCount = userMapper.register(username,password);
        if(resultCount == 0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    @Override
    public ServerResponse<String> checkValidUsername(String username){
        if(org.apache.commons.lang3.StringUtils.isNotBlank(username)){
            //开始校验
                int resultCount = userMapper.checkUsername(username);

                if(resultCount > 0 ){
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
        }else{
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

}
